package com.xuanzheng.company.servlet;

import com.google.gson.Gson;
import com.xuanzheng.company.entity.User;
import com.xuanzheng.company.util.DBUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;

/**
 * 获取待处理通知数量的Servlet
 */
@WebServlet("/pendingNotifications")
public class PendingNotificationsServlet extends HttpServlet {
    
    private final Gson gson = new Gson();
    
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) 
            throws ServletException, IOException {
        
        response.setContentType("application/json;charset=UTF-8");
        response.setHeader("Cache-Control", "no-cache");
        
        PrintWriter out = response.getWriter();
        Map<String, Object> result = new HashMap<>();
        
        try {
            // 检查用户登录状态
            HttpSession session = request.getSession(false);
            if (session == null) {
                response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
                result.put("success", false);
                result.put("message", "请先登录");
                out.print(gson.toJson(result));
                return;
            }
            
            User user = (User) session.getAttribute("user");
            if (user == null) {
                response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
                result.put("success", false);
                result.put("message", "请先登录");
                out.print(gson.toJson(result));
                return;
            }
            
            Map<String, Integer> notifications = new HashMap<>();
            
            // 根据用户角色获取不同的待处理事件数量
            switch (user.getRole()) {
                case 2: // 系统管理员
                    notifications = getAdminNotifications();
                    break;
                case 1: // 公司负责人
                    notifications = getManagerNotifications(user.getCompanyId());
                    break;
                case 0: // 普通用户
                    notifications = getEmployeeNotifications(user.getId());
                    break;
                default:
                    notifications = new HashMap<>();
            }
            
            result.put("success", true);
            result.put("notifications", notifications);
            out.print(gson.toJson(result));
            
        } catch (Exception e) {
            e.printStackTrace();
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            result.put("success", false);
            result.put("message", "服务器内部错误");
            out.print(gson.toJson(result));
        }
        
        out.flush();
        out.close();
    }
    
    /**
     * 获取系统管理员的待处理通知数量
     */
    private Map<String, Integer> getAdminNotifications() throws SQLException {
        Map<String, Integer> notifications = new HashMap<>();
        
        try (Connection conn = DBUtil.getConnection()) {
            // 待审核的系统使用申请
            String sql = "SELECT COUNT(*) as count FROM system_application WHERE status = 0";
            try (PreparedStatement pstmt = conn.prepareStatement(sql)) {
                ResultSet rs = pstmt.executeQuery();
                
                if (rs.next()) {
                    int count = rs.getInt("count");
                    if (count > 0) {
                        notifications.put("system-applications", count);
                    }
                }
            } catch (SQLException e) {
                // 如果表不存在，记录日志但不抛出异常
                System.out.println("system_application表可能不存在: " + e.getMessage());
            }
        } catch (SQLException e) {
            System.err.println("获取管理员通知时数据库连接失败: " + e.getMessage());
            e.printStackTrace();
        }
        
        return notifications;
    }
    
    /**
     * 获取公司负责人的待处理通知数量
     */
    private Map<String, Integer> getManagerNotifications(String companyId) throws SQLException {
        Map<String, Integer> notifications = new HashMap<>();
        
        try (Connection conn = DBUtil.getConnection()) {
            // 待审核的入职申请
            String sql1 = "SELECT COUNT(*) as count FROM company_employee WHERE company_id = ? AND status = 0";
            PreparedStatement pstmt1 = conn.prepareStatement(sql1);
            pstmt1.setString(1, companyId);
            ResultSet rs1 = pstmt1.executeQuery();
            
            if (rs1.next()) {
                int count = rs1.getInt("count");
                if (count > 0) {
                    notifications.put("employee-applications", count);
                }
            }
            
            // 待审核的离职申请（status=3表示申请离职）
            String sql2 = "SELECT COUNT(*) as count FROM company_employee WHERE company_id = ? AND status = 3";
            PreparedStatement pstmt2 = conn.prepareStatement(sql2);
            pstmt2.setString(1, companyId);
            ResultSet rs2 = pstmt2.executeQuery();
            
            if (rs2.next()) {
                int count = rs2.getInt("count");
                if (count > 0) {
                    notifications.put("resignation-applications", count);
                }
            }
            
            // 待确认的任务（status=1表示完成待确认）
            String sql3 = "SELECT COUNT(*) as count FROM task WHERE company_id = ? AND status = 1";
            try {
                PreparedStatement pstmt3 = conn.prepareStatement(sql3);
                pstmt3.setString(1, companyId);
                ResultSet rs3 = pstmt3.executeQuery();
                
                if (rs3.next()) {
                    int count = rs3.getInt("count");
                    if (count > 0) {
                        notifications.put("task-management", count);
                    }
                }
            } catch (SQLException e) {
                // 如果task表不存在，忽略这个错误
                System.out.println("Task table might not exist: " + e.getMessage());
            }
        }
        
        return notifications;
    }
    
    /**
     * 获取普通用户的待处理通知数量
     */
    private Map<String, Integer> getEmployeeNotifications(String userId) throws SQLException {
        Map<String, Integer> notifications = new HashMap<>();
        
        try (Connection conn = DBUtil.getConnection()) {
            // 待完成的个人任务（status=0表示派遣中）
            String sql = "SELECT COUNT(*) as count FROM task WHERE employee_id = ? AND status = 0";
            try {
                PreparedStatement pstmt = conn.prepareStatement(sql);
                pstmt.setString(1, userId);
                ResultSet rs = pstmt.executeQuery();
                
                if (rs.next()) {
                    int count = rs.getInt("count");
                    if (count > 0) {
                        notifications.put("my-tasks", count);
                    }
                }
            } catch (SQLException e) {
                // 如果task表不存在，忽略这个错误
                System.out.println("Task table might not exist: " + e.getMessage());
            }
        }
        
        return notifications;
    }
}